package com.ligq.h265toupinpush.toupin

import android.media.projection.MediaProjection
import android.util.Log
import org.java_websocket.WebSocket
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer
import java.net.InetSocketAddress

class SocketLive {
    private lateinit var webSocket: WebSocket
    private lateinit var h26xEncode: CodeLiveH26X
    private val webSocketServer = object : WebSocketServer(InetSocketAddress(9001)) {
        override fun onOpen(conn: WebSocket?, handshake: ClientHandshake?) {
            webSocket = conn!!
        }

        override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) {

        }

        override fun onMessage(conn: WebSocket?, message: String?) {

        }

        override fun onError(conn: WebSocket?, ex: Exception?) {

        }

        override fun onStart() {

        }

    }

    fun sendData(data: ByteArray) {
        if (this::webSocket.isInitialized && webSocket.isOpen) {
            webSocket.send(data)
        }
    }

    fun start(encodeType: Int, mediaProjection: MediaProjection) {
        webSocketServer.start()
        webSocket.send(encodeType.toString())
        h26xEncode = CodeLiveH26X(encodeType, mediaProjection, this)
        h26xEncode.start()
    }

    fun close() {
        try {
            webSocket.close()
            webSocketServer.stop()
        } catch (e: Exception) {
            Log.e(TAG, "close: ", e)
        }
    }
}